package cz.apnetis.fitweb.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.Widget;

import cz.apnetis.fitweb.shared.Food;
import cz.apnetis.gwt.client.ResultTableEditable;
import cz.apnetis.gwt.client.TableModelEditable;

public class FoodWidget extends Composite {

  private static FoodWidgetUiBinder uiBinder = GWT
  .create(FoodWidgetUiBinder.class);

  private final FoodServiceAsync foodService;

  private final FoodTableModel foodTableModel = new FoodTableModel();

  interface FoodWidgetUiBinder extends UiBinder<Widget, FoodWidget> {
  }

  @UiField
  ResultTableEditable<Food, TableModelEditable> table;

  public FoodWidget(final FoodServiceAsync foodService) {
    this.foodService = foodService;
    this.foodTableModel.setFoodService(foodService);
    init();
  }

  public FoodWidget() {
    this.foodService = GWT.create(FoodService.class);
    this.foodTableModel.setFoodService(this.foodService);
    init();
  }

  private final void init() {
    initWidget(uiBinder.createAndBindUi(this));

    reload();
  }

  /** Food service which is used for async communication */
  public final FoodServiceAsync getFoodService() {
    return this.foodService;
  }

  /** Handler which is call when user click on any label. This hide label, and
   * show edit box */
  public class WidgetClick implements ClickHandler {

    /** Label which own this handler */
    private final FocusWidget widget;

    public WidgetClick(final FocusWidget newWidget) {
      this.widget = newWidget;
    }

    @Override
    public void onClick(final ClickEvent event) {
      this.widget.setEnabled(true);
    }
  }

  /** Method which reload data for table etc. */
  public final void reload() {
    this.foodTableModel.loadPrevious(this.table);
  }

  @UiFactory
  public final ResultTableEditable<Food, TableModelEditable> makeResultTable() {
    return new ResultTableEditable<Food, TableModelEditable>(this.foodTableModel);
  };
}
